<?php
namespace App\Components\Twig;

use App\Components\Admin\Menu;
use App\Components\Admin\XsrfToken;
use App\Models\System\SystemConfig;
use Psr\Http\Message\UriInterface;
use Slim\Interfaces\RouteParserInterface;

class TwigRuntimeExtension
{
    protected $routeParser;

    protected $basePath = '';

    protected $uri;

    public function __construct(RouteParserInterface $routeParser, UriInterface $uri, string $basePath = '')
    {
        $this->routeParser = $routeParser;
        $this->uri = $uri;
        $this->basePath = $basePath;
    }

    public function url(string $route, array $parameters = [], bool $absolute = false): string
    {
        if ($route == '') {
            $uri = $this->uri;
        } elseif (strpos($route, '/') === 0) {
            $uri = $this->uri->withPath($route);
        } else {
            $currentPath = $this->uri->getPath();
            $currentPathLevel = substr_count($currentPath, '/');
            $routeLevel = substr_count($route, '/') + 1;
            if ($routeLevel > $currentPathLevel) {
                $route = '/' . $route;
                return $this->url($route, $parameters, $absolute);
            }
            for ($i = 0; $i < $routeLevel; $i++) {
                $currentPath = substr($currentPath, 0, strrpos($currentPath, '/'));
            }

            $uri = $this->uri->withPath($currentPath . '/' . $route);
        }
        $uri = $uri->withQuery(http_build_query($parameters));

        $url = $uri->__toString();
        if ($absolute === false) {
            $url = str_replace($uri->getScheme() . '://' . $uri->getHost(), '', $url);
        }

        return $url;
    }

    public function csrf()
    {
        $xsrf = XsrfToken::generate();

        setcookie(XsrfToken::$cookieName, $xsrf[0], time() + 7200, '/', '', false, true);

        $xsrfStr = '<input type="hidden" name="' . XsrfToken::$csrfTokenName;
        $xsrfStr .= '" value="' . $xsrf[1];
        $xsrfStr .= '">';
        return $xsrfStr;
    }

    public function menu(int $type = 1): array
    {
        $menu = Menu::currentMenu();
        if ($type == 1) {
            foreach ($menu as $k => $v) {
                if (isset($v['current']) && $v['current'] == true) {
                    unset($menu[$k]['children']);
                }
            }
            return $menu;
        } else {
            $return = [];
            foreach ($menu as $v) {
                if (isset($v['current']) && $v['current'] == true) {
                    $return = $v['children'] ?? [];
                }
            }
            return $return;
        }
    }

    public function config($keys, $default = '')
    {
        $keys = explode('.', $keys);
        $keys = array_values(array_filter($keys));
        if (!isset($keys[0])) {
            return $default;
        }
        $configRs = SystemConfig::getConfig($keys[0]);
        foreach ($keys as $k => $v) {
            if ($k == 0) {
                continue;
            }
            if (!isset($configRs[$v])) {
                $configRs = null;
                break;
            }
            $configRs = $configRs[$v];
        }
        return $configRs ?? $default;
    }

    public function view(string $keys)
    {
        $viewRs = \App\Models\System\SystemUserView::getView(\App\Models\System\SystemUser::getIdByToken());
        if ($keys == 'sidebar_view') {
            if (isset($viewRs['sidebar_color'])) {
                if (isset($viewRs['sidebar_view']) && $viewRs['sidebar_view'] == 'light') {
                    return 'sidebar-light-' . $viewRs['sidebar_color'];
                } else {
                    return 'sidebar-dark-' . $viewRs['sidebar_color'];
                }
            } else {
                return 'sidebar-dark-primary';
            }
        }
        if (isset($viewRs[$keys])) {
            return $viewRs[$keys];
        }
        return '';
    }

    public function inputImg(string $name, string $value = null)
    {
        $inputStr = '<div class="row">';
        if (isset($value[0])) {
            $inputStr .= '<div class="col-sm-4">';
            $inputStr .= '<div class="card">';
            $inputStr .= '<img class="img-thumbnail" src="' . $value . '" data-name="' . $name . '">';
            $inputStr .= '<div class="card-img-overlay bg-secondary" style="opacity: 0;">';
            $inputStr .= '<div class="d-flex flex-row justify-content-end align-items-start">';
            $inputStr .= '<button type="button" class="btn btn-tool img-tool-view"><i class="fas fa-expand"></i></button>';
            $inputStr .= '<button type="button" class="btn btn-tool img-tool-clear"><i class="fas fa-times"></i></button>';
            $inputStr .= '</div>';
            $inputStr .= '</div>';
            $inputStr .= ' </div>';
            $inputStr .= '</div>';
            $inputStr .= '<div class="col-sm-8">';
            $inputStr .= '<input type="file" class="my_pond" id="' . $name . '">';
            $inputStr .= '<input type="hidden" name="admin_logo" value="' . $value . '">';
            $inputStr .= '</div>';
        } else {
            $inputStr .= '<div class="col-sm-12">';
            $inputStr .= '<input type="file" class="my_pond" id="' . $name . '">';
            $inputStr .= '<input type="hidden" name="admin_logo" value="">';
            $inputStr .= '</div>';
        }
        $inputStr .= '</div>';
        return $inputStr;
    }
}
